﻿using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using BLL;
using Model;
using Common;
using AdminWeb.Filter;
using Microsoft.AspNetCore.Http;

namespace AdminWeb.Controllers
{
    [Area("Admin")]
    public class HomeController : Controller
    {

        [CheckAdminLogin]
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Login(string id)
        {
            string mess = "";
            switch(id)
            {
                case "p":
                    mess = "<div class='alert alert-info'><button type='button' class='close' data-dismiss='alert'>×</button><strong>密码错误</strong></div>";
                    break;
                case "no":
                    mess = "<div class='alert alert-info'><button type='button' class='close' data-dismiss='alert'>×</button><strong>账号不存在</strong></div>";
                    break;
                default:
                    mess = "";
                    break;
            }
            ViewBag.Mess = mess;
            return View();
        }

        /// <summary>
        /// 登陆验证
        /// </summary>
        /// <returns></returns>
        public ActionResult LoginSubmit()
        {
            string username = Request.Form["username"];
            string password= Request.Form["password"];
            string loginstate= Request.Form["loginstate"];
            
            MemberBLL bll = new MemberBLL();
            Member model = bll.GetModel(username);
            if(model!=null)
            {
                if(model.mem_pwd.Equals(Utils.MD5(password)))
                {
                    HttpContext.Session.SetString("adminuser", JSONHelper.SerializeObject(model));
                    //加密存cookie
                    string adminuser_e = Utils.AESEncrypt(model.mem_login + "|" + model.mem_pwd);
                    if (loginstate=="on")
                    {
                        Response.Cookies.Append("adminuser_e", adminuser_e, new CookieOptions { Path = "/", Expires = DateTime.Now.AddMonths(1) });
                    }
                    else
                    {
                        Response.Cookies.Append("adminuser_e", adminuser_e);
                    }

                    Response.Cookies.Append("adminuser", username, new CookieOptions { Path = "/", Expires = DateTime.Now.AddMonths(1) });
                    return Redirect("/Admin/Home/Index");
                }
                else
                {
                    return Redirect("/Admin/Home/Login/p");
                }
            }
            else
            {
                return Redirect("/Admin/Home/Login/no");
            }
            
        }

    }
}